package cn.SiFuLan.utils;

import java.sql.*;
import java.util.List;

public class BaseDao {
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private final String url = "jdbc:mysql://localhost:3306/SiFuLan";
    private final String uname = "root";
    private final String upwd = "050412";
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public Connection getConnection(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url,uname,upwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public void CloseAll(Connection conn, Statement stem, ResultSet rs){
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stem != null){
            try {
                stem.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public ResultSet executeQuery(String sql, List<Object> sz){
        Connection conn = getConnection();
        PreparedStatement pstem = null;
        try {
            pstem = conn.prepareStatement(sql);
            if (sz!=null && sz.size()>0){
                for (int i=0;i<sz.size();i++){
                    pstem.setObject(i+1,sz.get(i));
                }
            }
            return pstem.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public Boolean executeUpdate(String sql,List<Object> sz){
        Connection conn = getConnection();
        PreparedStatement pstem = null;
        int row = 0;
        try {
            pstem = conn.prepareStatement(sql);
            if (sz!=null && sz.size()>0){
                for (int i=0;i<sz.size();i++){
                    pstem.setObject(i+1,sz.get(i));
                }
            }
            row = pstem.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row >0;
    }
}
